package org.raymond.iworks.study.netty.atguigu.netty.inout2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class InClientHandler2 extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("{} channelRegistered", ctx.name());
        ctx.fireChannelRegistered();
    }
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.info("{} channelUnregistered", ctx.name());
        ctx.fireChannelUnregistered();
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("{} channelActive", ctx.name());
        // 证明上一个inBoundHandler里面的writeAndFlush是异步执行的,因为对端会在sleep期间收到消息
        Thread.sleep(1000);
        ctx.fireChannelActive();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("{} handlerAdded", ctx.name());
        super.handlerAdded(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("{} channelInactive", ctx.name());
        ctx.fireChannelInactive();
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("{} channelRead {}", ctx.name(), msg);
        // 尝试继续传播到下一个inBoundhandler,但是已经没有下一个inBoundhandler了, netty会抛弃msg,并警告
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("{} channelReadComplete", ctx.name());
        ctx.fireChannelReadComplete();
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("{} userEventTriggered", ctx.name());
        ctx.fireUserEventTriggered(evt);
    }
    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        log.info("{} channelWritabilityChanged", ctx.name());
        ctx.fireChannelWritabilityChanged();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("{} handlerRemoved", ctx.name());
        super.handlerRemoved(ctx);
    }

    @Override
    @SuppressWarnings("deprecation")
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        log.info("{} exceptionCaught", ctx.name());
        ctx.close();
    }
}
